import { HttpClient } from '../utils/HttpClient';
import { HealthData, SleepData, ApiResponse } from '../types';
import distributedDataObject from '@ohos.data.distributedDataObject';
import hilog from '@ohos.hilog';

export interface WatchHealthData {
  steps: number;
  distance: number;
  calories: number;
  activeMinutes: number;
  heartRateData: number[];
  stressLevel: number;
  timestamp: number;
}

export interface WatchSleepData {
  sleepDate: string;
  bedtime: string;
  sleepStart: string;
  wakeTime: string;
  getUpTime: string;
  totalDuration: number;
  deepSleep: number;
  lightSleep: number;
  remSleep: number;
  awakeDuration: number;
  sleepEfficiency: number;
  sleepScore: number;
  wakeUpCount: number;
  timestamp: number;
}

export class DataSyncService {
  private httpClient: HttpClient;
  private distributedObject: distributedDataObject.DistributedDataObject | null = null;
  private isInitialized: boolean = false;
  private syncQueue: any[] = [];
  private isSyncing: boolean = false;
  private lastSyncTime: number = 0;

  constructor() {
    this.httpClient = new HttpClient();
    this.initializeDistributedData();
  }

  /**
   * 初始化分布式数据对象
   */
  private async initializeDistributedData(): Promise<void> {
    try {
      // 创建分布式数据对象
      this.distributedObject = distributedDataObject.create(globalThis.abilityContext, {
        latestHealthData: {},
        lastSyncTime: 0,
        syncStatus: 'idle'
      });

      // 设置会话ID（用于设备间同步）
      const sessionId = 'health_sync_' + Date.now();
      await this.distributedObject.setSessionId(sessionId);

      // 监听数据变化
      this.distributedObject.on('change', (sessionId: string, fields: string[]) => {
        hilog.info(0x0000, 'DataSync', 'Distributed data changed: %{public}s', JSON.stringify(fields));
        this.handleDistributedDataChange(fields);
      });

      this.isInitialized = true;
      hilog.info(0x0000, 'DataSync', 'Distributed data object initialized successfully');
    } catch (error) {
      hilog.error(0x0000, 'DataSync', 'Failed to initialize distributed data: %{public}s', error.message);
    }
  }

  /**
   * 处理分布式数据变化
   */
  private handleDistributedDataChange(fields: string[]): void {
    if (fields.includes('latestHealthData')) {
      hilog.info(0x0000, 'DataSync', 'Health data updated from other device');
      // 可以在这里触发UI更新通知
      this.notifyDataUpdate();
    }
  }

  /**
   * 从华为Watch同步健康数据
   */
  public async syncFromWatch(): Promise<boolean> {
    try {
      hilog.info(0x0000, 'DataSync', 'Starting health data sync from watch');

      // 模拟从华为Watch获取数据
      // 实际实现中需要使用HarmonyOS的Health Kit API
      const watchData = await this.getWatchHealthData();
      
      if (watchData) {
        // 添加到同步队列
        this.addToSyncQueue('health', watchData);
        
        // 立即同步到服务器
        await this.processSyncQueue();
        
        return true;
      }
      
      return false;
    } catch (error) {
      hilog.error(0x0000, 'DataSync', 'Failed to sync from watch: %{public}s', error.message);
      return false;
    }
  }

  /**
   * 从华为Watch同步睡眠数据
   */
  public async syncSleepFromWatch(): Promise<boolean> {
    try {
      hilog.info(0x0000, 'DataSync', 'Starting sleep data sync from watch');

      const sleepData = await this.getWatchSleepData();
      
      if (sleepData) {
        this.addToSyncQueue('sleep', sleepData);
        await this.processSyncQueue();
        return true;
      }
      
      return false;
    } catch (error) {
      hilog.error(0x0000, 'DataSync', 'Failed to sync sleep data from watch: %{public}s', error.message);
      return false;
    }
  }

  /**
   * 模拟获取华为Watch健康数据
   * 实际实现中需要调用HarmonyOS Health Kit API
   */
  private async getWatchHealthData(): Promise<WatchHealthData | null> {
    try {
      // 这里应该调用真实的Health Kit API
      // 目前返回模拟数据
      const mockData: WatchHealthData = {
        steps: Math.floor(Math.random() * 10000) + 5000,
        distance: Math.round((Math.random() * 8 + 2) * 100) / 100,
        calories: Math.floor(Math.random() * 500) + 1500,
        activeMinutes: Math.floor(Math.random() * 120) + 30,
        heartRateData: this.generateMockHeartRateData(),
        stressLevel: Math.floor(Math.random() * 50) + 25,
        timestamp: Date.now()
      };

      hilog.info(0x0000, 'DataSync', 'Mock health data generated: steps=%{public}d', mockData.steps);
      return mockData;
    } catch (error) {
      hilog.error(0x0000, 'DataSync', 'Failed to get watch health data: %{public}s', error.message);
      return null;
    }
  }

  /**
   * 模拟获取华为Watch睡眠数据
   */
  private async getWatchSleepData(): Promise<WatchSleepData | null> {
    try {
      const yesterday = new Date();
      yesterday.setDate(yesterday.getDate() - 1);
      
      const bedtime = new Date(yesterday);
      bedtime.setHours(23, 30, 0, 0);
      
      const sleepStart = new Date(bedtime);
      sleepStart.setMinutes(sleepStart.getMinutes() + 15);
      
      const wakeTime = new Date(yesterday);
      wakeTime.setDate(wakeTime.getDate() + 1);
      wakeTime.setHours(7, 0, 0, 0);
      
      const getUpTime = new Date(wakeTime);
      getUpTime.setMinutes(getUpTime.getMinutes() + 10);
      
      const totalDuration = Math.floor((wakeTime.getTime() - sleepStart.getTime()) / (1000 * 60));
      const deepSleep = Math.floor(totalDuration * 0.25);
      const lightSleep = Math.floor(totalDuration * 0.55);
      const remSleep = Math.floor(totalDuration * 0.15);
      const awakeDuration = totalDuration - deepSleep - lightSleep - remSleep;

      const mockSleepData: WatchSleepData = {
        sleepDate: yesterday.toISOString().split('T')[0],
        bedtime: bedtime.toISOString(),
        sleepStart: sleepStart.toISOString(),
        wakeTime: wakeTime.toISOString(),
        getUpTime: getUpTime.toISOString(),
        totalDuration,
        deepSleep,
        lightSleep,
        remSleep,
        awakeDuration,
        sleepEfficiency: Math.round((totalDuration / ((getUpTime.getTime() - bedtime.getTime()) / (1000 * 60))) * 100),
        sleepScore: Math.floor(Math.random() * 30) + 70,
        wakeUpCount: Math.floor(Math.random() * 3),
        timestamp: Date.now()
      };

      hilog.info(0x0000, 'DataSync', 'Mock sleep data generated: duration=%{public}d minutes', mockSleepData.totalDuration);
      return mockSleepData;
    } catch (error) {
      hilog.error(0x0000, 'DataSync', 'Failed to get watch sleep data: %{public}s', error.message);
      return null;
    }
  }

  /**
   * 生成模拟心率数据
   */
  private generateMockHeartRateData(): number[] {
    const heartRates: number[] = [];
    const baseHeartRate = 75;
    
    for (let i = 0; i < 24; i++) { // 24小时的心率数据
      const variation = Math.random() * 20 - 10; // -10到+10的变化
      const heartRate = Math.max(60, Math.min(120, baseHeartRate + variation));
      heartRates.push(Math.round(heartRate));
    }
    
    return heartRates;
  }

  /**
   * 添加数据到同步队列
   */
  private addToSyncQueue(type: string, data: any): void {
    this.syncQueue.push({
      type,
      data,
      timestamp: Date.now(),
      retryCount: 0
    });

    hilog.info(0x0000, 'DataSync', 'Added %{public}s data to sync queue', type);
  }

  /**
   * 处理同步队列
   */
  private async processSyncQueue(): Promise<void> {
    if (this.isSyncing || this.syncQueue.length === 0) {
      return;
    }

    this.isSyncing = true;

    try {
      const batch = this.syncQueue.splice(0, 10); // 每次处理最多10条记录
      
      for (const item of batch) {
        try {
          await this.syncSingleItem(item);
          hilog.info(0x0000, 'DataSync', 'Successfully synced %{public}s data', item.type);
        } catch (error) {
          hilog.error(0x0000, 'DataSync', 'Failed to sync %{public}s data: %{public}s', item.type, error.message);
          
          // 重试机制
          if (item.retryCount < 3) {
            item.retryCount++;
            this.syncQueue.push(item);
          }
        }
      }

      // 更新分布式数据
      await this.updateDistributedData();
      
    } finally {
      this.isSyncing = false;
      
      // 如果队列中还有数据，继续处理
      if (this.syncQueue.length > 0) {
        setTimeout(() => this.processSyncQueue(), 5000);
      }
    }
  }

  /**
   * 同步单个数据项
   */
  private async syncSingleItem(item: any): Promise<void> {
    if (item.type === 'health') {
      await this.syncHealthDataToServer(item.data);
    } else if (item.type === 'sleep') {
      await this.syncSleepDataToServer(item.data);
    }
  }

  /**
   * 同步健康数据到服务器
   */
  private async syncHealthDataToServer(data: WatchHealthData): Promise<void> {
    const syncData = {
      record_date: new Date().toISOString().split('T')[0],
      steps: data.steps,
      distance: data.distance,
      calories: data.calories,
      active_minutes: data.activeMinutes,
      heart_rate_data: data.heartRateData,
      stress_level: data.stressLevel,
      data_source: 'huawei_watch'
    };

    const response = await this.httpClient.post('/health/sync', syncData);
    
    if (!response.success) {
      throw new Error(response.message || 'Health data sync failed');
    }
  }

  /**
   * 同步睡眠数据到服务器
   */
  private async syncSleepDataToServer(data: WatchSleepData): Promise<void> {
    const syncData = {
      sleep_date: data.sleepDate,
      bedtime: data.bedtime,
      sleep_start: data.sleepStart,
      wake_time: data.wakeTime,
      get_up_time: data.getUpTime,
      total_duration: data.totalDuration,
      deep_sleep: data.deepSleep,
      light_sleep: data.lightSleep,
      rem_sleep: data.remSleep,
      awake_duration: data.awakeDuration,
      sleep_efficiency: data.sleepEfficiency,
      sleep_score: data.sleepScore,
      wake_up_count: data.wakeUpCount,
      data_source: 'huawei_watch'
    };

    const response = await this.httpClient.post('/health/sleep/sync', syncData);
    
    if (!response.success) {
      throw new Error(response.message || 'Sleep data sync failed');
    }
  }

  /**
   * 更新分布式数据
   */
  private async updateDistributedData(): Promise<void> {
    if (!this.distributedObject || !this.isInitialized) {
      return;
    }

    try {
      const latestData = await this.getLatestHealthData();
      
      this.distributedObject.latestHealthData = latestData;
      this.distributedObject.lastSyncTime = Date.now();
      this.distributedObject.syncStatus = 'completed';

      this.lastSyncTime = Date.now();
      
      hilog.info(0x0000, 'DataSync', 'Distributed data updated successfully');
    } catch (error) {
      hilog.error(0x0000, 'DataSync', 'Failed to update distributed data: %{public}s', error.message);
    }
  }

  /**
   * 获取最新健康数据
   */
  private async getLatestHealthData(): Promise<any> {
    try {
      const response = await this.httpClient.get('/health/latest');
      return response.success ? response.data : {};
    } catch (error) {
      hilog.error(0x0000, 'DataSync', 'Failed to get latest health data: %{public}s', error.message);
      return {};
    }
  }

  /**
   * 启动自动同步
   */
  public startAutoSync(): void {
    // 立即执行一次同步
    this.syncFromWatch();
    
    // 设置定时同步（每5分钟）
    setInterval(() => {
      this.syncFromWatch();
    }, 5 * 60 * 1000);

    // 设置睡眠数据同步（每天早上8点）
    this.scheduleDailySleepSync();

    hilog.info(0x0000, 'DataSync', 'Auto sync started');
  }

  /**
   * 安排每日睡眠数据同步
   */
  private scheduleDailySleepSync(): void {
    const now = new Date();
    const tomorrow = new Date(now);
    tomorrow.setDate(tomorrow.getDate() + 1);
    tomorrow.setHours(8, 0, 0, 0);

    const msUntilTomorrow = tomorrow.getTime() - now.getTime();

    setTimeout(() => {
      this.syncSleepFromWatch();
      
      // 设置每日重复
      setInterval(() => {
        this.syncSleepFromWatch();
      }, 24 * 60 * 60 * 1000);
    }, msUntilTomorrow);
  }

  /**
   * 停止自动同步
   */
  public stopAutoSync(): void {
    // 这里应该清除所有的定时器
    // 简化实现，实际需要保存定时器引用
    hilog.info(0x0000, 'DataSync', 'Auto sync stopped');
  }

  /**
   * 获取同步状态
   */
  public getSyncStatus(): { 
    isInitialized: boolean; 
    isSyncing: boolean; 
    queueLength: number; 
    lastSyncTime: number 
  } {
    return {
      isInitialized: this.isInitialized,
      isSyncing: this.isSyncing,
      queueLength: this.syncQueue.length,
      lastSyncTime: this.lastSyncTime
    };
  }

  /**
   * 手动触发同步
   */
  public async manualSync(): Promise<boolean> {
    try {
      hilog.info(0x0000, 'DataSync', 'Manual sync triggered');
      
      const healthSyncResult = await this.syncFromWatch();
      const sleepSyncResult = await this.syncSleepFromWatch();
      
      return healthSyncResult || sleepSyncResult;
    } catch (error) {
      hilog.error(0x0000, 'DataSync', 'Manual sync failed: %{public}s', error.message);
      return false;
    }
  }

  /**
   * 清除同步队列
   */
  public clearSyncQueue(): void {
    this.syncQueue = [];
    hilog.info(0x0000, 'DataSync', 'Sync queue cleared');
  }

  /**
   * 通知数据更新
   */
  private notifyDataUpdate(): void {
    // 这里可以发送全局事件通知UI更新
    // 例如使用emitter或者全局状态管理
    try {
      globalThis.emitter?.emit('healthDataUpdated', {
        timestamp: Date.now(),
        source: 'distributed'
      });
    } catch (error) {
      hilog.warn(0x0000, 'DataSync', 'Failed to notify data update: %{public}s', error.message);
    }
  }

  /**
   * 销毁服务
   */
  public destroy(): void {
    try {
      this.stopAutoSync();
      
      if (this.distributedObject) {
        this.distributedObject.off('change');
        this.distributedObject = null;
      }
      
      this.clearSyncQueue();
      this.isInitialized = false;
      
      hilog.info(0x0000, 'DataSync', 'DataSyncService destroyed');
    } catch (error) {
      hilog.error(0x0000, 'DataSync', 'Failed to destroy DataSyncService: %{public}s', error.message);
    }
  }
}